// pages/wallet/mine/mine.js
const util = require('../../../utils/util')
// 获取当前月份
function getCurrentMonth(){
  let date = new Date();
  let YY = date.getFullYear();
  let MM = date.getMonth() + 1;
  let DD = date.getDate();
  MM = MM < 10 ? '0'+MM : MM;
  DD = DD < 10 ? '0'+DD : DD;
  return `${YY}`
}

// 格式换人民币
function formatMoney(value){
  let str = Math.abs(value).toString()
  let txt = '';
  if(str.includes('.')){
    let i = str.lastIndexOf('.')
    let value = str.slice(i+1)
    if(value.length==1){
      txt = str+"0"
    }
    else {
      txt = str+"";
    }
  }
  else {
     txt = str+".00"
  }
  return txt;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: getCurrentMonth(),
    array: ['2025', '2024','2023','2022', '2021','2020'],
    account:'',
    datetime:'',
    yearList: [],
    currentYearIncome: '0.00',
    currentYearOutcome:  '0.00',
    currentYearTotal:  '0.00',
     // 定义数组获取本地存储的数据
     elements: [],
  }, 
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    
    let date = this.data.array[e.detail.value]
    this.setData({
      index: e.detail.value,
      date: date
    })
    this.getCurrentYearList();
  },
  // 编写方法获取本地存储的数据
  getElements(){
      let elements = wx.getStorageSync('ELEMENTS_JIZHANG');
     //  console.log("1.0",elements)
      if(elements){
        this.setData({
          elements
        })

        let newArr = elements.map(item=>{
          item.money = formatMoney(item.money)
          return item;
        })

        this.setData({
          yearList: newArr
        })
      }
   },

  // 编写函数获取当月数据
  getCurrentYearList(){
    let elements = this.data.elements;
    let date = this.data.date && this.data.date.slice(0,4);
    console.log("年:",date)
    let arr = elements.filter(item=>{
        if(item.datetime.includes(date)){
          return item;
        }
    })
    if(arr.length == 0) {
      this.setData({
        currentYearIncome: formatMoney(0),
        currentYearOutcome: formatMoney(0),
        currentYearTotal: formatMoney(0),
        yearList: []
      })
    }
    else {
        // 当前月份的存钱
        let  currentYearIncome = 0
        // 当前月份的支出
        let  currentYearOutcome = 0
        // 循环当前月份的数组
        for(let i = 0 ; i < arr.length ; i ++){
            if(arr[i].num == '1'){
              currentYearOutcome+=(arr[i].money) * 1000
            }
            if(arr[i].num == '2'){
              currentYearIncome+=(arr[i].money) * 1000
            }
        }
        let currentYearTotal = currentYearIncome - currentYearOutcome;

        // 整合数据
        let newArr = arr.map(item=> {
           item.total = 0;
           item.income = 0;
           item.outcome = 0;
           item.year = item.datetime.slice(0,7);
           if(item.num == '1'){
              item.outcome+= (item.money - 0) * 1000
           }
           if(item.num == '2'){
              item.income+= (item.money - 0) * 1000
           }
           item.total = item.income -  item.outcome;
           return item;
        })
        // console.log('---->',newArr)

        // let result = newArr.map(item=> {
        //     item.outcome = formatMoney(item.outcome/1000)
        //     item.income = formatMoney(item.income/1000)
        //     item.total = formatMoney(item.total/1000)
        //     return item;
        // })

        // 定义月份
        let months = ['/01/','/02/','/03/','/04/','/05/','/06/','/07/','/08/','/09/','/10/','/11/','/12/']     
        
        // 定义空数组
        let arr2 = [];
        // 循环 months 和 newArr 数组
        for(let i = 0 ; i < months.length ; i ++){
            arr2[i] = {
              income:0,
              outcome:0,
              total: 0,
              month: months[i]
            }
            for(let j = 0 ; j < newArr.length ; j ++){
                if(newArr[j].datetime.includes(months[i])){
                  console.log("月份:",months[i])
                  if(newArr[j].num == '1'){
                    arr2[i].outcome += newArr[j].outcome;
                  }
                  if(newArr[j].num == '2'){
                    arr2[i].income += newArr[j].income;
                  }
                  arr2[i].total +=  newArr[j].total;
                }
            }
        }

        // 整合数据
        let result2 = arr2.map(item=> {
          item.outcome = formatMoney(item.outcome/1000)
          item.income = formatMoney(item.income/1000)
          item.total = formatMoney(item.total/1000)
          return item;
      })
        

        // 赋值
        this.setData({
          currentYearIncome: formatMoney(currentYearIncome / 1000),
          currentYearOutcome: formatMoney(currentYearOutcome / 1000),
          currentYearTotal: formatMoney(currentYearTotal / 1000),
          yearList: result2
        })
    }
  },

  // 编写方法 给用户设置一个随机的账号
  createAccount(){
      let account = wx.getStorageSync('ACCOUNT');
      let datetime = wx.getStorageSync('DATETIME');
      if(account){
         this.setData({account,datetime})
      }
      else {
          // 存储首次使用的时间
          const dt = new Date();
          let datetime = util.formatTime(dt);
          wx.setStorageSync('DATETIME', datetime)
          // 随机账号
          let acc = Math.random().toString().slice(-4);
          this.setData({
            account: acc,
            datetime: datetime
          })
          // 把账号存储在本地
          wx.setStorageSync('ACCOUNT', acc)
        
      }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.createAccount();
    this.getElements();
    this.getCurrentYearList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getElements();
    this.getCurrentYearList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})